import os
import json
import re

def create_display_names_mapping(directory):
    mapping = {}
    demo_dir = os.path.join(directory, 'demo')
    
    def process_file(filepath, root_dir):
        """处理单个文件，返回安全文件名和是否需要重命名"""
        filename = os.path.basename(filepath)
        if filename == 'display_names.json':
            return None, None, False
            
        if re.search(r'[^\x00-\x7F]', filename):
            # 创建ASCII文件名
            safe_name = re.sub(r'[^a-zA-Z0-9._-]', '_', filename)
            
            # 处理重复文件名
            base_safe_name = safe_name
            counter = 1
            while os.path.exists(os.path.join(os.path.dirname(filepath), safe_name)):
                name_parts = os.path.splitext(base_safe_name)
                safe_name = f"{name_parts[0]}_{counter}{name_parts[1]}"
                counter += 1
            
            return safe_name, filename, True
        
        return filename, filename, False

    def scan_directory(dir_path):
        """扫描目录并处理文件"""
        for root, dirs, files in os.walk(dir_path):
            # 处理文件
            for filename in files:
                filepath = os.path.join(root, filename)
                safe_name, display_name, needs_rename = process_file(filepath, dir_path)
                
                if safe_name and display_name:
                    # 生成相对路径
                    rel_path = os.path.relpath(filepath, directory)
                    safe_rel_path = os.path.join(
                        os.path.dirname(rel_path),
                        safe_name
                    ).replace('\\', '/')
                    
                    display_rel_path = os.path.join(
                        os.path.dirname(rel_path),
                        display_name
                    ).replace('\\', '/')
                    
                    # 添加到映射
                    mapping[safe_rel_path] = display_rel_path
                    
                    # 如果需要重命名
                    if needs_rename:
                        new_path = os.path.join(root, safe_name)
                        try:
                            if filepath != new_path:
                                os.rename(filepath, new_path)
                                print(f"Renamed: {filepath} -> {new_path}")
                        except Exception as e:
                            print(f"Error renaming {filepath} to {new_path}: {e}")

    # 扫描demo目录
    if os.path.exists(demo_dir):
        print(f"Scanning demo directory: {demo_dir}")
        scan_directory(demo_dir)
    else:
        print(f"Demo directory not found: {demo_dir}")
        return

    # 如果映射为空，说明没有需要处理的文件
    if not mapping:
        print("No files need mapping")
        return

    # 保存映射文件
    mapping_path = os.path.join(directory, 'display_names.json')
    with open(mapping_path, 'w', encoding='utf-8') as f:
        json.dump({
            "toDisplay": mapping,
            "toSafe": {v: k for k, v in mapping.items()}
        }, f, ensure_ascii=False, indent=2)

    print(f"\nGenerated display names mapping at: {mapping_path}")
    print("\nMappings generated:")
    for safe_name, display_name in mapping.items():
        print(f"{safe_name} -> {display_name}")

if __name__ == '__main__':
    base_dir = './resources/files/auto-office'
    create_display_names_mapping(base_dir)